<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rule" class="form-container">

      <sticky :z-index="10" class="sub-navbar published">
        <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm">
          发布商品
        </el-button>
        <el-button v-loading="loading" style="margin-left: 10px;" type="warning" @click="cancelForm">
          取消
        </el-button>
      </sticky>

      <div class="createPost-main-container">
        <el-row>
          <el-col :span="24">
            <el-form-item style="margin-bottom: 40px;" prop="title">
              <MDinput v-model="postForm.name" :maxlength="100" name="name" required>
                商品名
              </MDinput>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item style="margin-bottom: 40px;" label-width="70px" label="主标签:">
          <el-select v-model="postForm.mainType" placeholder="商品主标签" allow-create filterable default-first-option>
            <el-option
              v-for="item in typeList"
              :key="item.name"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>

        <el-form-item style="margin-bottom: 40px;" label-width="70px" label="关键字:">
          <el-input v-model="postForm.keywords" :rows="1" type="textarea" class="article-textarea" autosize placeholder="请输入关键字" />
          <span v-show="keywordsLength" class="word-counter">{{ keywordsLength }} 字</span>
        </el-form-item>

        <el-form-item style="margin-bottom: 40px;" label-width="70px" label="价格:">
          <el-input-number v-model="postForm.prices" :min="1" />
        </el-form-item>
        <el-form-item prop="content" style="margin-bottom: 30px;">
          <Tinymce ref="editor" v-model="postForm.content" :height="400" />
        </el-form-item>

        <el-form-item label="image">
          <Upload v-model="postForm.image" />
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import MDinput from '@/components/MDinput'
import Upload from '@/components/Upload/SingleImage3'
import Sticky from '@/components/Sticky' // 粘性header组件
import { findProudct, createProduct, fetchProductTypeList } from '@/api/product'
const defaultForm = {
  name: '', // 商品名
  content: '', // 商品内容
  keywords: '默认关键字', // 商品关键字
  mainType: '默认主标签', // 商品主类型
  subType: '默认次标签', // 商品次类型
  imageList: [], // 图片列表,
  image: '', // 图片的url
  prices: 1,
  id: undefined
}
export default {
  name: 'ProductDetail',
  components: { Tinymce, MDinput, Sticky, Upload },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '' || value === undefined) {
        const mes = rule.field + '为必传项'
        this.$message({
          message: mes,
          type: 'error'
        })
        callback(new Error(mes))
      } else {
        callback()
      }
    }
    const validateInteger = (rule, value, callback) => {
      if (!'^[1-9][0-9]*$'.test(value)) {
        const mes = rule.field + '必须为整数'
        this.$message({
          message: mes,
          type: 'warning'
        })
        callback(new Error(mes))
      } else {
        callback()
      }
    }

    return {
      postForm: Object.assign({}, defaultForm),
      loading: false,
      userListOptions: [],
      rule: {
        prices: [{ validator: validateInteger, trigger: 'blur' }, { validator: validateRequire }, { type: 'number', message: '价格必须为数字' }],
        image: [{ validator: validateRequire }],
        name: [{ validator: validateRequire }],
        content: [{ validator: validateRequire }]
      },
      tempRoute: {},
      typeList: []
    }
  },
  computed: {
    keywordsLength() {
      return this.postForm.keywords.length
    }
  },
  created() {
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    }
    fetchProductTypeList().then(res => {
      this.typeList = res
    })
    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    fetchData(id) {
      findProudct({ productId: id }).then(res => {
        this.postForm = res
        // set tagsview title
        this.setTagsViewTitle()
        // set page title
        this.setPageTitle()
      })
    },
    handleExceed(files, fileList) {
      this.$message.warning('您上传的图片超出了我们的限制!')
    },
    setTagsViewTitle() {
      const title = '编辑商品'
      const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.postForm.id}` })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    setPageTitle() {
      const title = '编辑商品'
      document.title = `${title} - ${this.postForm.id}`
    },
    cancelForm() {
      this.$router.go(-1)
    },
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.postForm.subType = this.postForm.mainType
          createProduct(this.postForm).then(res => {
            this.$notify({
              title: '成功',
              message: '发布商品成功',
              type: 'success',
              duration: 2000
            })
            this.$router.go(-1)
          })
          this.loading = false
        } else {
          this.$message({
            message: '商品提交校验失败',
            type: 'warning'
          })
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";
.createPost-container {
  position: relative;
  .createPost-main-container {
    padding: 40px 45px 20px 50px;
    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;
      .postInfo-container-item {
        float: left;
      }
    }
  }
  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}
.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
